﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NAnt.Core;
using NAnt.Core.Attributes;
using NAnt.Core.Types;
using System.Data.OleDb;

namespace NAntExt.Tasks
{
    /// <summary>
    /// The sql-scalar task which executes a sql statement then sets a property with the result.
    /// </summary>
    [TaskName("sql-scalar")]
    public class SqlScalarTask : Task
    {

        /// <summary>
        /// The connection string to use to connect to the database.
        /// </summary>
        [TaskAttribute("connectionString", Required = true)]
        [StringValidator(AllowEmpty = false)]
        public string ConnectionString { get; set; }

        /// <summary>
        /// The SQL to execute.
        /// </summary>
        [TaskAttribute("sql", Required = true)]
        [StringValidator(AllowEmpty = false)]
        public string Sql { get; set; }

        /// <summary>
        /// The property to set with the result value.
        /// </summary>
        [TaskAttribute("property", Required = true)]
        [StringValidator(AllowEmpty = false)]
        public string Property { get; set; }

        /// <summary>
        /// Entry point for the task.
        /// </summary>
        protected override void ExecuteTask()
        {
            try
            {
                using (var connection = new OleDbConnection(ConnectionString))
                {
                    connection.Open();
                    try
                    {
                        using (var command = new OleDbCommand(Sql, connection))
                        {
                            object scalarValue = command.ExecuteScalar();
                            string stringValue = (scalarValue == null)
                                ? string.Empty : Convert.ToString(scalarValue);
                            this.Properties[Property] = stringValue;
                        }
                    }
                    finally
                    {
                        connection.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                if (this.FailOnError)
                    throw new BuildException("sql-scalar task failed during execution due to an unhandled exception.", this.Location, ex);
                else
                    Log(Level.Error, "sql-scalar task failed during execution due to an unhanled exception. ex = {0}", ex);
            }
        }

    }
}
